import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:permission_handler/permission_handler.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Contacts App',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: ContactsPage(),
    );
  }
}

class ContactsPage extends StatefulWidget {
  @override
  _ContactsPageState createState() => _ContactsPageState();
}

class _ContactsPageState extends State<ContactsPage> {
  List<Contact> contacts = [];
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadContacts();
  }

  Future<void> _loadContacts() async {
    // 请求通讯录权限
    if (await Permission.contacts.request().isGranted) {
      List<Contact> contactList = await FlutterContacts.getContacts();
      setState(() {
        contacts = contactList;
        isLoading = false;
      });
    } else {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Contacts')),
      body: isLoading
          ? Center(child: CircularProgressIndicator())
          : contacts.isNotEmpty
              ? ListView.builder(
                  itemCount: contacts.length,
                  itemBuilder: (context, index) {
                    final contact = contacts[index];
                    return ListTile(
                      leading: CircleAvatar(
                        backgroundImage: contact.photo != null
                            ? MemoryImage(contact.photo!)
                            : AssetImage('assets/default_avatar.png') as ImageProvider,
                      ),
                      title: Text(contact.displayName ?? 'No Name'),
                      subtitle: Text(
                        contact.phones.isNotEmpty ? contact.phones.first.number ?? 'No Number' : 'No Number',
                      ),
                    );
                  },
                )
              : Center(child: Text('No contacts found')),
    );
  }
}
